package reduce.fz.com.reduce.abstracts;

import com.alibaba.fastjson.TypeReference;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;

import reduce.fz.com.reduce.bean.ServiceException;
import reduce.fz.com.reduce.bean.User;
import reduce.fz.com.reduce.bean.result.Result;
import reduce.fz.com.reduce.util.JsonUtil;
import reduce.fz.com.reduce.util.ReduceLog;
import reduce.fz.com.reduce.util.ToastUtil;

/**
 * Created by qingshengzheng on 15/7/26.
 */
public abstract class AbResponseListener<T> implements Response.Listener, ErrorListener {

    public AbResponseListener(TypeReference<Result<T>> typeReference) {
        this.typeReference = typeReference;
    }

    private TypeReference typeReference;

    public TypeReference getTypeReference() {
        return typeReference;
    }

    public void setTypeReference(TypeReference typeReference) {
        this.typeReference = typeReference;
    }

    @Override
    public void onErrorResponse(VolleyError volleyError) {
        ServiceException e = null;
        if (volleyError instanceof TimeoutError) {
            ToastUtil.showMessage("请求超时，请检查网络是否正常!");
            error(new ServiceException("999", "请求超时，请检查网络是否正常!"));
        } else {
            ToastUtil.showMessage("系统异常!");
            error(new ServiceException("E1", "系统异常"));
        }
        ReduceLog.e(volleyError);
    }

    @Override
    public void onResponse(Object o) {
        Result result = (Result) JsonUtil.convert(o.toString(), getTypeReference());
        if (!result.isSuccess()) {
            ToastUtil.showMessage(result.getDesc());
            ServiceException e = new ServiceException(result.getErrorcode(), result.getDesc());
            error(e);
        } else responseInfo(result);
    }

    public abstract void error(ServiceException e) ;
    public abstract void responseInfo(Result<T> data);

}
